package com.jacky.demo.widget;

import android.content.Context;
import android.support.v7.widget.AppCompatSeekBar;
import android.util.AttributeSet;
import android.widget.SeekBar;

/**
 * 因为原有的SeekBar将Max设置为很小的情况下，到会导致滑动不顺畅，
 * 现修改部分逻辑，实现顺畅滑动，并且自动靠近离自己最近的节点
 */

public class SmoothSeekBar extends AppCompatSeekBar {

    public SmoothSeekBar(Context context) {
        super(context);
        init();
    }

    public SmoothSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SmoothSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

//    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
//    public SmoothSeekBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
//        super(context, attrs, defStyleAttr, defStyleRes);
//        init();
//    }

    private OnSeekBarChangeListener mListtener;
    private boolean isChangeProgress;

    private void init() {
        int max = super.getMax();
        if(max >= 100) return;

        isChangeProgress = true;
        setMax(100 * max);

        super.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(mListtener != null) {
                    mListtener.onProgressChanged(seekBar, getChangePro(progress), fromUser);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if(mListtener != null) {
                    mListtener.onStartTrackingTouch(seekBar);
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(mListtener != null) {
                    mListtener.onStopTrackingTouch(seekBar);
                }

                setProgress(getOriProgress() * 100);
            }
        });
    }

    @Override
    public void setOnSeekBarChangeListener(OnSeekBarChangeListener l) {
        if(isChangeProgress) {
            mListtener = l;
        } else {
            super.setOnSeekBarChangeListener(l);
        }
    }

    public int getOriMax() {
        return super.getMax() / 100;
    }

    public int getOriProgress() {
        return getChangePro(super.getProgress());
    }

    private int getChangePro(int progress) {
        float p = (float)progress / 100;
        return (int) (p + 0.5);
    }
}
